package com.example.app1.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.example.app1.LogUtil;
import com.example.app1.MainActivity;
import com.example.app1.R;
import com.example.app1.util.CacheChangeListener;
import com.example.app1.util.CacheKey;
import com.example.app1.util.HandleCommand;
import com.example.app1.util.MyConstants;
import com.example.app1.util.PlayStatus;
import com.example.app1.util.HandleTts;

import org.json.JSONException;
import org.json.JSONObject;

public class MyTextToSpeechService extends Service implements TextToSpeech.OnInitListener{
    private static final String TAG = "MyTextToSpeechService";
    private static final String CHANNEL_ID = "my_channel_id_khfh";
    private static final int NOTIFICATION_ID = 1;

    private NotificationManager notificationManager = null;
    private NotificationManagerCompat notificationManagerCompat = null;

    private TextToSpeech textToSpeech = null;
    private SharedPreferences sharedPreferences = null;
    private SharedPreferences.OnSharedPreferenceChangeListener changeListener = null;

    private HandleTts handleTts = null;
    private BroadcastReceiver broadcastReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.info(TAG, "onCreate");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            // 在这里执行针对 Android 11 的特定操作
            LogUtil.info(TAG, "当前设备等于或高于android11:" + android.os.Build.VERSION.SDK_INT);
        } else {
            // 当前设备运行的不是 Android 11
            LogUtil.info(TAG, "当前设备低于android11:" + android.os.Build.VERSION.SDK_INT);
        }
        this.textToSpeech = new TextToSpeech(getApplicationContext(), this);

        // 创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (this.notificationManager == null) {
                CharSequence name = "My Notification Channel";
                String description = "Channel description";
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
                channel.setDescription(description);

                // 注册通知渠道
                this.notificationManager = getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);

                // 创建通知
                Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                        .setContentTitle("Foreground Service")
                        .setContentText("Service is running in the foreground")
                        .setSmallIcon(R.drawable.notification_icon)
                        .build();
                startForeground(NOTIFICATION_ID, notification);
            }

        } else {
            if (this.notificationManagerCompat == null) {
                this.notificationManagerCompat = NotificationManagerCompat.from(this);
                Notification notification = new Notification.Builder(this)
                        .setContentTitle("Foreground Service")
                        .setContentText("Service is running in the foreground")
                        .setSmallIcon(R.drawable.notification_icon)
                        .build();

                startForeground(NOTIFICATION_ID, notification);
            }

        }

        broadcastReceiver = new BroadcastReceiver() {
            @SuppressLint("CommitPrefEdits")
            @Override
            public void onReceive(Context context, Intent intent) {
                String command = intent.getStringExtra("command");
                String id = "";
                if ("pause".equals(command)) {
                    HandleCommand.pause(sharedPreferences, handleTts);
                } else if ("stop".equals(command)) {
                    HandleCommand.stop(sharedPreferences, handleTts);
                } else if ("play".equals(command)) {
                    id = intent.getStringExtra("id");
                    String preUrlFlag = intent.getStringExtra("preUrl");
                    if (preUrlFlag != null && !"".equals(preUrlFlag.trim())) {
                        SharedPreferences.Editor edit = sharedPreferences.edit();
                        edit.putString(CacheKey.PRE_URL.name(), preUrlFlag);
                        edit.apply();
                    }
                    HandleCommand.play(sharedPreferences, handleTts, id);
                } else if ("next".equals(command)) {
                    HandleCommand.playNext(sharedPreferences, handleTts);
                } else if ("previous".equals(command)) {
                    HandleCommand.playPre(sharedPreferences, handleTts);
                } else if ("restore".equals(command)) {
                    String content = sharedPreferences.getString(CacheKey.CURRENT_CONTENT.name(), null);
                    String itemId = sharedPreferences.getString(CacheKey.CURRENT_ID.name(), null);
                    if (content != null && itemId != null && !content.trim().isEmpty() && !itemId.trim().isEmpty()) {
                        showContentToView(content.trim(), itemId.trim());
                    }
                }
                LogUtil.info(TAG, "receive " + command + " id:" + id);
            }
        };
        IntentFilter filter = new IntentFilter("myhandle");
        registerReceiver(broadcastReceiver, filter);
    }

    @Override
    public void onInit(int status) {
        // 这里是tts初始化结果
        LogUtil.info(TAG, "OnInit");
        if (status == TextToSpeech.SUCCESS) {
            LogUtil.info(TAG, "success init speech");

            if (this.sharedPreferences == null) {
                this.sharedPreferences = getSharedPreferences(MyConstants.CACHE_NAME, MODE_PRIVATE);
            }

            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString(CacheKey.STATUS.name(), PlayStatus.READY.name());
            edit.putString(CacheKey.CURRENT_CONTENT.name(), "");
            edit.putString(CacheKey.NEXT_ID.name(), "");
            edit.putString(CacheKey.MSG.name(), "");
            edit.putBoolean(CacheKey.Show_PAUSE.name(), false);
            edit.commit();  // 先初始化状态 章节内容 暂停隐藏

            if (this.handleTts == null) {
                this.handleTts = new HandleTts(sharedPreferences, this.textToSpeech);
            }
            if (this.changeListener == null) {
                this.changeListener = new CacheChangeListener(this.handleTts, this);
            }

            this.sharedPreferences.registerOnSharedPreferenceChangeListener(this.changeListener);
            this.showToast("初始化tts服务成功");
        } else {
            this.showToast("onInit 初始化tts服务失败");
            stopSelf();  // 初始化失败时停止服务
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.info(TAG, "Service onStartCommand");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onDestroy();
        LogUtil.info(TAG, "onDestroy");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            this.notificationManager.cancel(NOTIFICATION_ID);
        } else {
            this.notificationManagerCompat.cancel(NOTIFICATION_ID);
        }
        stopSelf();

        // 取消注册广播接收器
        unregisterReceiver(broadcastReceiver);
        // 取消前台服务
        stopForeground(true);
        if (this.sharedPreferences != null) {
            this.sharedPreferences.unregisterOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                    LogUtil.info(TAG, "destory unregisterOnSharedPreferenceChangeListener key:" + key);
                }
            });
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void updateNotify(String title, String text) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        @SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentIntent(pendingIntent)
                .build();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            this.notificationManager.notify(NOTIFICATION_ID, notification);
        } else {
            this.notificationManagerCompat.notify(NOTIFICATION_ID, notification);
        }
    }

    public void showToast(String msg) {
        // 显示toast消息
        try {
            Intent intent = new Intent("custom-action");
            JSONObject callbackData = new JSONObject();
            callbackData.put("msg", msg);
            callbackData.put("type", "toast");
            intent.putExtra("data", callbackData.toString());
            sendBroadcast(intent);  // 发送广播给界面
        } catch (JSONException e) {
            LogUtil.info(TAG, "showToast json格式错误：" + msg, e);
        }
    }

    public void showContentToView(String content, String id) {
        try {
            Intent intent = new Intent("custom-action");
            JSONObject callbackData = new JSONObject();
            callbackData.put("content", content);
            callbackData.put("id", id);
            intent.putExtra("data", callbackData.toString());
            sendBroadcast(intent);  // 发送广播给界面
        } catch (JSONException e) {
            LogUtil.info(TAG, "showContentToView json格式错误：" + id, e);
        }
    }

    public void changePauseButtonStatus(boolean isShow) {
        try {
            Intent intent = new Intent("custom-action");
            JSONObject callbackData = new JSONObject();
            callbackData.put("type", "changePauseButtonStatus");
            callbackData.put("isShow", isShow);
            intent.putExtra("data", callbackData.toString());
            sendBroadcast(intent);  // 发送广播给界面
        } catch (JSONException e) {
            LogUtil.info(TAG, "changePauseButtonStatus json格式错误：" + isShow, e);
        }
    }

    public void setCurrentIdx(String currentIdx) {
        try {
            if (currentIdx != null && !currentIdx.trim().isEmpty()) {
                Intent intent = new Intent("custom-action");
                JSONObject callbackData = new JSONObject();
                callbackData.put("type", "currentIdx");
                callbackData.put("currentIdx", currentIdx);
                intent.putExtra("data", callbackData.toString());
                sendBroadcast(intent);  // 发送广播给界面
            }
        } catch (JSONException e) {
            LogUtil.info(TAG, "setCurrentText json格式错误：" + currentIdx, e);
        }
    }

    public void showMsg(String msg) {
        LogUtil.info(TAG, msg);
        this.showContentToView(msg, "");
        textToSpeech.setOnUtteranceProgressListener(null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            textToSpeech.speak(msg, TextToSpeech.QUEUE_FLUSH, null, "uniqueId2");
        } else {
            textToSpeech.speak(msg, TextToSpeech.QUEUE_FLUSH, null);
        }
    }

}
